<style scoped>
  .weui-form-preview__hd label, .weui-form-preview__hd em {
    font-size: .9em !important;
  }
  .weui-loadmore_line .weui-loadmore__tips {
    background-color: #eee;
  }
  .rj-cell.max span{
    font-size: 16px;
    padding-right: 20px;
  }
  .rj-cell label {
    color: #333;
    font-size: 14px;
    width: 44%;
    display: inline-block;
    padding: 5px 3%;
    text-align: right;
  }
  .rj-cell span {
    font-size: 14px;
    color: #333;
    display: inline-block;
    width: 50%;
  }
  .rj-cell.note label{
    float: left;
  }
  .rj-cell.note span{
    width: 80%;
    display: inline-block;
  }
  .weui-cells {
    margin-top: 0;
  }
  .weui-cells_form {
    background: #fbfbfb;
  }
  .weui-cell {
    background: #fff;
  }
  #acts span {
    font-size: 14px;
  }
  .halfbtn {
    display: inline-block;
    width: 49%;
  }
  .weui-label{
    /*width: 130px;*/
    text-align: left;
  }

  .weui-select {
    height: auto;
    line-height: normal;
  }
  *{
    list-style:none;
  }
  #acts {
    font-size: 0;
  }
  #acts span {
    font-size: 14px;
  }
  .fixbtn {
    position: absolute;
    right: -10px;
    font-size: 12px;
    bottom: -10px;
    color: #ccc;
    z-index: 1000;
    background: #fff;
    padding: 0 5px;
  }
</style>
<template>
  <div class="sendcar">
    <div style="height: 50px; line-height: 50px; background: #f7f7f7; text-align: center; font-size: 16px; border-bottom: 1px solid #bdbbbc; position: relative">
      {{title}}
      <a href="javascript:;" @click="$router.back(-1)" style="position: absolute; left: 10px; top: 8px">
        <img src="../../assets/back.png" style="width: 20px" />
      </a>
    </div>
    <div class="weui-cells weui-cells_form">
      <form action="" method="post" id="formid">
        <input type="hidden" name="entity.type" :value="type">
        <div class="cellgroup">
          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">所属公司</label></div>
            <div class="weui-cell__bd">
              <input type="hidden" ref="orgname" name="entity.orgname">
              <select class="weui-select" name="entity.orgid" v-model="orgid" id="org">
                <option selected=""  v-for="(item, index) in organizations" :key="item.guid" :value="item.guid">{{item.name}}</option>
              </select>
            </div>
          </div>
          <div class="weui-cell" v-if="type != 1">
            <div class="weui-cell__hd"><label class="weui-label">调整类型</label></div>
            <div class="weui-cell__bd">
              <select class="weui-select" name="entity.type">
                <option value="2" selected>调整出库</option>
                <option value="3">调整入库</option>
              </select>
            </div>
          </div>
          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">{{fromSrTitle}}</label></div>
            <div class="weui-cell__bd">
              <input type="hidden" ref="fromsrname" name="entity.fromsrname">
              <select class="weui-select" name="entity.fromsrguid" v-model="fromsrguid" id="fromsr">
                <option selected=""  v-for="(item, index) in rooms" :key="item.guid" :value="item.guid">{{item.name}}</option>
              </select>
            </div>
          </div>
          <div class="weui-cell" v-if="showTosr">
            <div class="weui-cell__hd"><label class="weui-label">调入库房</label></div>
            <div class="weui-cell__bd">
              <input type="hidden" ref="tosrname" name="entity.tosrname">
              <select class="weui-select" name="entity.tosrguid" v-model="tosrguid" id="tosr">
                <option selected=""  v-for="(item, index) in rooms" :key="item.guid" :value="item.guid">{{item.name}}</option>
              </select>
            </div>
          </div>
<!--          <div class="weui-cell">-->
<!--            <div class="weui-cell__hd"><label class="weui-label">调拨重量(吨)</label></div>-->
<!--            <div class="weui-cell__bd">-->
<!--              <input class="weui-input weight" type="number" name="shiftweight" placeholder="请输入重量" />-->
<!--            </div>-->
<!--          </div>-->
          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">备注</label></div>
            <div class="weui-cell__bd">
              <textarea class="weui-textarea" name="entity.remark" placeholder="请输备注内容" rows="2"></textarea>
            </div>
          </div>
        </div>
        <TransferApplyItem ref="applyItem" v-for="(item, index) in oitems" :key="index" :parentType="type" :itemNo="item" :isLast="index+1 == oitems.length" :orgid="orgid" :roomid="fromsrguid" @doAddItem="addItem(index + 1)" @doDelItem="delItem"></TransferApplyItem>
        <div class="weui-btn-area">
          <a class="weui-btn weui-btn_primary halfbtn subbtn"  href="javascript:" @click="send">提交</a>
          <a class="weui-btn weui-btn_primary halfbtn"  href="javascript:" @click="$router.back(-1)" id="sub">返回</a>
        </div>
      </form>
    </div>
  </div>
</template>

<script>
  import TransferApplyItem from "./TransferApplyItem";
  export default {
    name: 'AddTransferApply',
    data () {
      return {
        openid: localStorage.openid,
        organizations: [],
        rooms: [],
        oitems: [0],
        type: 1,
        fromsrguid: '',
        tosrguid: '',
        orgid: ''
      }
    },
    computed: {
      title: function() {
        return this.type == 1 ? '库房调拨录入' : '库存调整录入';
      },
      fromSrTitle: function() {
        return this.type == 1 ? '调出库房' : '库房';
      },
      showTosr: function() {
        return this.type == 1 ? true : false;
      }
    },
    components: {TransferApplyItem},
    created() {
      window.addEventListener('setItem', ()=> {
        this.openid = localStorage.getItem('openid');
      })
    },
    mounted () {
      //type 1-库房调拨，2，3-库存调整
      this.type = this.$route.query.type;

      //获取公司
      this.getOrganization()
      //获取库房
      this.getRooms();
    },
    watch: {
      'orgid': function (val) {
        this.$refs.orgname.value = $('#org').find('option:selected').text();
      },
      'fromsrguid': function (val) {
        this.$refs.fromsrname.value = $('#fromsr').find('option:selected').text();
      },
      'tosrguid': function (val) {
        this.$refs.tosrname.value = $('#tosr').find('option:selected').text();
      },
      // 'type': function (val) {
      //   if (val == 1) {
      //     this.showTosr = true;
      //     this.fromSrTitle = '出库库房';
      //   } else {
      //     this.showTosr = false;
      //     this.fromSrTitle = '库房';
      //   }
      // },
    },
    methods: {
      addItem: function(index) {
        this.oitems.push(index);
      },
      delItem: function() {
        this.oitems.pop();
      },
      getOrganization: function() {
        this.axios({
          method: 'get',
          url: '/produce/Produceplan!getOrgbyWh.action',
          params: {}
        }).then((response) => {
          if (response.data.status == 'true') {
            this.organizations = response.data.result;
            this.orgid = response.data.result[0].guid;
            this.$nextTick(function () {
              this.$refs.orgname.value = response.data.result[0].name;
            })
          } else if(response.data.status == 'false') {
            this.toastError(response.data.result);
          } else {
            this.toastError("系统错误");
          }

        })
      },
      getRooms: function() {
        let functype = this.type == 1 ? 12 : 5;
        this.axios({
          method: 'get',
          url: '/sales/Salespermission!getPermisForStore.action?openid=' + this.openid,
          params: {functionTypes: functype, type: 1}
        }).then(response => {
          if (response.data.msg == 'true') {
            this.rooms = response.data.storeroom;
            this.fromsrguid = response.data.storeroom[0].guid;
            this.$nextTick(function () {
              this.$refs.fromsrname.value = response.data.storeroom[0].name;
            })
          } else if (response.data.msg == 'loginout') {
            this.toastError('请重新登录');
          } else {
            this.toastText('获取库房数据失败');
          }
        });
      },
      send: function() {
        let productItem = this.$refs.applyItem;

        if (!this.checkEmy('weight')) {
          this.toastText('重量有误！');
          return false;
        }
        if (!this.checkEmy('product')) {
          this.toastText('产品有误！');
          return false;
        }
        if (productItem[0].type == 1 && !this.checkEmy('spec')) {
          this.toastText('产品规格有误！');
          return false;
        }
        if (!this.checkProduct()) {
          this.toastText('货品明细产品重复！')
          return false;
        }
        //防止重复提交
        $('.subbtn').attr("disabled",true).css("pointer-events","none");

        let postData = this.serialize2Obj($("#formid").serializeArray());

        this.axios({
          method: 'post',
          url: '/produce/Transferapply!saveApplyInfo.action',
          params: postData
        }).then(response => {
          //恢复提交按钮可点击
          $('.subbtn').attr('disabled', false).css("pointer-events","auto");

          if(response.data.msg == "success"){
            this.toastText('操作成功!');
            this.$router.push({name: 'TransferApplyList', query:{type: this.type}});
          }else if (response.data.msg == 'outlogin'){
            this.toastError('请重新登录!');
          }else if (response.data.msg == 'error'){
            this.toastError('系统错误!');
          }
        }).catch(function (error) {
          //恢复提交按钮可点击
          $('.subbtn').attr('disabled', false).css("pointer-events","auto");
          this.toastError('系统错误');
        });;

      },
      //判断明细产品是否重复
      checkProduct: function () {
        let parr1 = [];
        let parr2 = [];
        for (let i=0; i<$('.oitem').length; i++) {
          let tempHouse = $('.strhouse').eq(i).val();
          let tempProduct = $('.product').eq(i).val();
          let tempSpec = $('.spec').eq(i).val();
          parr1.push({[tempHouse]: tempProduct + tempSpec});
          parr2.push({[tempHouse]: tempProduct + tempSpec});
        }
        //json数组去重
        for (var i = 0; i < parr2.length; i++) {
          for (var j =i+1; j <parr2.length; ) {
            if (Object.keys(parr2[i])[0] == Object.keys(parr2[j])[0] && Object.values(parr2[i])[0] == Object.values(parr2[j])[0] ) {
              parr2.splice(j, 1);//去除重复的对象；
            }else {
              j++;
            }
          }
        }
        return parr1.length == parr2.length ? true : false;
      }
    }
  }


</script>
